import { ApiResponse, ChannelList } from '@/types/data'
import { ChannelAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { hasToken } from '@/utils/storage'
import { getChannels, setChannels } from '@/utils/storageChannel'

// 获取用户频道
export function getChannel (): RootThunkAction {
  return async (dispatch) => {
    if (hasToken()) {
      // 1. 发请求
      const res = await request.get<ApiResponse<{ channels: ChannelList }>>(
        'user/channels'
      )
      console.log('用户登录了，获取频道', res.data.data.channels)
      // 2. 保存信息
      dispatch({
        type: 'channel/getChannel',
        payload: res.data.data.channels
      })
    } else {
      // 没有登录，从本地取一次
      const channels = getChannels()
      if (channels.length > 0) {
        console.log('直接使用本地频道')
        dispatch({
          type: 'channel/getChannel',
          payload: channels
        })
      } else {
        // 1. 发请求
        const res = await request.get<ApiResponse<{ channels: ChannelList }>>(
          'user/channels'
        )
        console.log('用户没有登录，获取频道', res.data.data.channels)
        // 2. 保存信息
        dispatch({
          type: 'channel/getChannel',
          payload: res.data.data.channels
        })

        // 3.持久化
        setChannels(res.data.data.channels)
      }
    }
  }
}

// 获取所有的频道
export function getAllChannel (): RootThunkAction {
  return async (dispatch) => {
    // 1. 发请求
    const res = await request.get<ApiResponse<{ channels: ChannelList }>>(
      '/channels'
    )
    console.log('获取所有频道', res.data.data.channels)
    // 2. 保存信息
    dispatch({
      type: 'channel/saveAllChannels',
      payload: res.data.data.channels
    })
  }
}
// 设置当前选中的频道的id
export function setActive (id: string): ChannelAction {
  return {
    type: 'channel/setActive',
    id
  }
}
